﻿using DotNetCore.CAP.Messages;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Service.Framework;
using Service.Framework.AppStartup;

namespace Service.CAP.EventBus;

/// <summary>
/// 
/// </summary>
public class ServiceCapEventBus : StartupModule<ServiceCapEventBus>
{
    public override int Order { get; set; } = 110;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="webApplicationBuilder"></param>
    public override void ConfigureServices(WebApplicationBuilder webApplicationBuilder)
    {
        AppSettings<EventBusConfigure> appSettings = webApplicationBuilder.Services.BuildServiceProvider()
            .GetService<AppSettings<EventBusConfigure>>();

        ILogger logger = webApplicationBuilder.Services.BuildServiceProvider().GetService<ILogger<IEvent>>();
        webApplicationBuilder.Services.AddSingleton<IEventPublisher, CapPublisher>();
        var rabbitMQ = appSettings.Instance.RabbitMQ;
        if (rabbitMQ != null)
        {
            webApplicationBuilder.Services.AddCap(x =>
            {
                x.UseRabbitMQ(option =>
                {
                    option.HostName = rabbitMQ.HostName;
                    option.VirtualHost = rabbitMQ.VirtualHost;
                    option.Port = rabbitMQ.Port;
                    option.UserName = rabbitMQ.UserName;
                    option.Password = rabbitMQ.Password;
                });
                if (rabbitMQ.CapDataConfig != null)
                {
                    x.UseMySql(rabbitMQ.CapDataConfig.ConnectionString);
                }
                if (webApplicationBuilder.Environment.IsDevelopment())
                {
                    x.UseDashboard();
                }

                ////默认值：1,消费者线程并行处理消息的线程数，当这个值大于1时，将不能保证消息执行的顺序。
                x.ConsumerThreadCount = 1;
                x.SucceedMessageExpiredAfter = 10 * 24 * 3600;
                x.FailedThresholdCallback = (e) =>
                {
                    if (e.MessageType == MessageType.Publish)
                    {
                        logger.LogError("Cap发送消息失败：{Message}", JsonConvert.SerializeObject(e.Message));
                    }
                    else if (e.MessageType == MessageType.Subscribe)
                    {
                        logger.LogError("Cap接收消息失败：{Message}", JsonConvert.SerializeObject(e.Message));
                    }
                };
            });
        }


    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="webApplication"></param>
    public override void Configure(WebApplication webApplication)
    {
    }
}